import re

from qturboframe.lib.webdriver.exceptions import SeleniumError
from hslib.webdriver.data_change import (deal_datetime, deal_time)
from .base_element import BaseElement


class CalendarM97(BaseElement):
    """
    Jres2.0的m97日历控件

    :Attributes:
     - _driver: 控件所在的当前webdriver对象
     - _element: 控件元素webelement对象
     - timeout: 步骤操作的超时时间

    :Example:
     - 例1: CalendarM97(webelement)
     - 例2: CalendarM97({By.CLASS_NAME:'class_name','text':'文本信息'})
     - 例3: CalendarM97({By.CLASS_NAME:'class_name','text':'文本信息'}, father=driver)
     - 例4: CalendarM97({By.CLASS_NAME:'class_name','text':'文本信息'}, father=webelement)
    """

    def __init__(self, element_para=None, father=None, timeout=5):
        super().__init__(element_para, father, timeout)
        
    # 赋值
    def set_value(self, inputele, text):
        """
        Jres2.0的m97日历组件赋值

        :Args:
         - inputele: m97日历控件组
         - text: 日期值

        :Example:
         - 例1: calendarM97.set_value('20210219')
         - 例2: calendarM97.set_value('今天')
         - 例2: calendarM97.set_value('today')
        """
        re_displayinline = r'display:\s*inline;*'
        re_none = r'display:\s*none;*'
        inputele.secure_click()
        # 切换到主页
        self._driver.switch_to.default_content()
        # 切换到日历frame
        frame_list = self._driver.get_all_frame()
        frame_index = len(frame_list) - 1
        self._driver.switch_to.frame(frame_index)
        # 日历选择
        date_div = self._driver.find_element_by_attribute('class name', 'WdateDiv', timeout=self.timeout)
        if text == '今天' or text.lower() == 'today':
            today_div = date_div.find_element_by_attribute('xpath', './div[@id=\'dpControl\']',
                                                           timeout=self.timeout)
            today_button = today_div.find_element_by_attribute('xpath', './input[@type=\'button\']',
                                                               'value:今天', timeout=self.timeout)
            today_button.secure_click()
        else:
            textlist = text.split(' ')
            if len(textlist) == 2:
                date = textlist[0]
                date = deal_datetime(date)
                year, month, day = date.split('/')
                time = textlist[1]
                time = deal_time(time)
                hour, minute, second = time.split(':')
            else:
                if ':' in textlist[0]:
                    time = textlist[0]
                    time = deal_time(time)
                    hour, minute, second = time.split(':')
                    year = None
                    month = None
                    day = None
                else:
                    date = textlist[0]
                    date = deal_datetime(date)
                    year, month, day = date.split('/')
                    hour = None
                    minute = None
                    second = None
            # 设置year
            year_div = date_div.exist('css selector', 'div#dpTitle>div:nth-child(4)', timeout=1)
            if year_div and year:
                year_div.find_element_by_attribute('xpath', './input[@class=\'yminput\']').secure_click()
                self.__set_year(year_div, year)
            # 设置month
            month_div = date_div.exist('css selector', 'div#dpTitle>div:nth-child(3)', timeout=1)
            if month_div and month:
                month_div.find_element_by_attribute('xpath', './input[@class=\'yminput\']').secure_click()
                self.__set_month(month_div, month)
            # 设置day
            try:
                date_table = date_div.exist('xpath', './div[3]/table[@class="WdayTable"]', timeout=1)
            except SeleniumError:
                date_table = None
            except NoDisplayError:
                date_table = None
            if date_table and day:
                self.__set_day(date_table, day)
            # 获取timediv
            time_div = date_div.exist('css selector', 'div#dpTime', timeout=1)
            if time_div and hour:
                if not re.search(re_none, time_div.get_attribute('style')):
                    # 设置hour
                    self.__set_hour(time_div, hour)
                    # 设置minute
                    self.__set_minute(time_div, minute)
                    # 设置second
                    self.__set_second(time_div, second)
            # 点击确定按钮
            try:
                sure_button = date_div.find_element_by_attribute("xpath", ".//*[@id='dpControl']/input[3]", timeout=1)
                sure_button.secure_click(timeout=1)
            except SeleniumError:
                pass

    def __set_year(self, year_div, year):
        year_table = year_div.find_element_by_attribute('xpath', './div/table[1]', timeout=self.timeout)
        year_prev = year_div.find_element_by_attribute('xpath', './div/table[2]/tbody/tr/td[1]',
                                                       timeout=self.timeout)
        year_next = year_div.find_element_by_attribute('xpath', './div/table[2]/tbody/tr/td[3]',
                                                       timeout=self.timeout)
        yearmin = year_table.find_element_by_attribute('xpath', './tbody/tr[1]/td[1]').text
        yearmax = year_table.find_element_by_attribute('xpath', './tbody/tr[5]/td[2]').text
        if int(year) < int(yearmin):
            year_prev.secure_click()
            self.__set_year(year_div, year)
        elif int(year) > int(yearmax):
            year_next.secure_click()
            self.__set_year(year_div, year)
        else:
            td = year_table.find_element_by_attribute('xpath', './tbody/*/td[text()="' + year + '"]',
                                                      timeout=self.timeout)
            td.secure_click()

    def __set_month(self, month_div, month):
        month_table = month_div.find_element_by_attribute('xpath', './div/table', timeout=self.timeout)
        tdlist = month_table.find_elements_by_attribute('xpath', './tbody/*/td', timeout=self.timeout)
        month_list = ['一月', '二月', '三月', '四月', '五月', '六月',
                      '七月', '八月', '九月', '十月', '十一', '十二']
        for td in tdlist:
            if td.text == month_list[int(month)-1]:
                td.secure_click()
                break

    def __set_day(self, day_table, day):
        day_td = day_table.find_element_by_attribute(
            'xpath', './tbody/*/td[@class="Wwday" or @class="Wday" or @class="Wselday"]',
            'text:' + str(int(day)), timeout=self.timeout)
        day_td.secure_click()

    def __set_hour(self, time_div, hour):
        hour_input = time_div.find_element_by_attribute('xpath', './table/tbody/tr[1]/td[1]/input[1]',
                                                        timeout=self.timeout)
        hour_input.clear()
        hour_input.send_keys(hour)

    def __set_minute(self, time_div, minute):
        minute_input = time_div.find_element_by_attribute('xpath', './table/tbody/tr[1]/td[1]/input[3]',
                                                          timeout=self.timeout)
        minute_input.clear()
        minute_input.send_keys(minute)

    def __set_second(self, time_div, second):
        second_input = time_div.find_element_by_attribute('xpath', './table/tbody/tr[1]/td[1]/input[5]',
                                                          timeout=self.timeout)
        second_input.clear()
        second_input.send_keys(second)
    
    @staticmethod
    def is_readonly_for_group(self, inputs):
        """
        Jres2.0的m97日历框组只读校验是否成功

        :Args:
         - inputs: m97日历框控件组

        :Returns:
            控件组均是只读状态则返回True，否则返回False

        :Example:
         - 例1: calendarM97.is_readonly_for_group(inputs)
        """
        for inputele in inputs:
            if not inputele.is_readonly():
                return False
        else:
            return True
